package com.planshare.activity;

import java.net.MalformedURLException;
import java.net.URL;

import org.json.rpc.client.HttpJsonRpcClientTransport;
import org.json.rpc.client.JsonRpcInvoker;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

import com.planshare.object.User;
import com.planshare.service.UserService;
import com.planshare.util.UserUtil;

public class SignUpActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_up);
    }

    public void signUpClicked(View v) {
    	final ProgressDialog dialog = new ProgressDialog(SignUpActivity.this);
		dialog.setMessage("Signing up...");
		dialog.setIndeterminate(true);
		dialog.setCancelable(false);
		dialog.show();
		new Thread(new Runnable() {
			public void run() {

				EditText emailEditText = (EditText) findViewById(R.id.signUpEmail);
				EditText passwordEditText = (EditText) findViewById(R.id.signUpPassword);
				EditText nameEditText = (EditText) findViewById(R.id.signUpName);
				final String email = emailEditText.getText().toString();
				final String password = passwordEditText.getText().toString();
				final String name = nameEditText.getText().toString();

				HttpJsonRpcClientTransport transport;
				try {
					transport = new HttpJsonRpcClientTransport(new URL(UserUtil.userServiceUrl));
					JsonRpcInvoker invoker = new JsonRpcInvoker();
					UserService userService = invoker.get(transport, "user",
							UserService.class);

					User user = new User();
					user.setEmail(email);
					user.setPassword(password);
					user.setName(name);
					
					final User newUser = userService.signUpUser(user);

					SignUpActivity.this.runOnUiThread(new Runnable() {
						public void run() {
							final AlertDialog alertDialog = new AlertDialog.Builder(
									SignUpActivity.this).create();
							alertDialog.setButton("OK",
									new DialogInterface.OnClickListener() {
										public void onClick(DialogInterface dialog,
												int which) {
											dialog.dismiss();
										}
									});
							if (newUser == null) {
								alertDialog.setMessage("Could not sign up");
								dialog.dismiss();
								alertDialog.show();
							} else {
								dialog.dismiss();
								UserUtil.user = newUser;
								Intent intent = new Intent(SignUpActivity.this,
										HomeActivity.class);
								startActivity(intent);
							}
						}
					});
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}).start();
    }

    
}
